package cn.heyige.backend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.heyige.backend.entity.HexagramDO;
import cn.heyige.backend.entity.YaoCiDO;
import cn.heyige.backend.mapper.HexagramMapper;
import cn.heyige.backend.mapper.YaoCiMapper;
import cn.heyige.backend.service.HexagramService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * 卦象服务实现类 - 精简版
 *
 * 专注于核心卦象管理功能，提高系统性能和可维护性
 * 增强数据验证和错误处理
 *
 * @author CodeBuddy
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HexagramServiceImpl extends ServiceImpl<HexagramMapper, HexagramDO> implements HexagramService {
    
    private final HexagramMapper hexagramMapper;
    private final YaoCiMapper yaoCiMapper;
    
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int MAX_PAGE_SIZE = 100;
    
    @Override
    public Optional<HexagramDO> getHexagramByCode(String code) {
        // 参数校验
        if (!StringUtils.hasText(code)) {
            throw new IllegalArgumentException("卦象编码不能为空");
        }

        try {
            HexagramDO hexagram = hexagramMapper.findBySymbol(code);
            return hexagram != null ? Optional.of(hexagram) : Optional.empty();
        } catch (Exception e) {
            log.error("根据卦象编码获取卦象失败: code={}", code, e);
            throw new RuntimeException("根据卦象编码获取卦象失败: " + e.getMessage());
        }
    }
    
    @Override
    public Optional<HexagramDO> getHexagramByName(String name) {
        // 参数校验
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("卦名不能为空");
        }

        try {
            HexagramDO hexagram = hexagramMapper.findByName(name);
            return hexagram != null ? Optional.of(hexagram) : Optional.empty();
        } catch (Exception e) {
            log.error("根据卦名获取卦象失败: name={}", name, e);
            throw new RuntimeException("根据卦名获取卦象失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<HexagramDO> getAllHexagrams(Integer pageNum, Integer pageSize) {
        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            return page(new Page<>(actualPageNum, actualPageSize));
        } catch (Exception e) {
            log.error("获取所有卦象失败: pageNum={}, pageSize={}", actualPageNum, actualPageSize, e);
            throw new RuntimeException("获取所有卦象失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<YaoCiDO> getYaoCiByHexagramId(Integer hexagramId) {
        // 参数校验
        if (hexagramId == null) {
            throw new IllegalArgumentException("卦象ID不能为空");
        }

        try {
            return yaoCiMapper.findByHexagramId(hexagramId);
        } catch (Exception e) {
            log.error("根据卦象ID获取爻辞失败: hexagramId={}", hexagramId, e);
            throw new RuntimeException("根据卦象ID获取爻辞失败: " + e.getMessage());
        }
    }
    
    @Override
    public YaoCiDO getYaoCiByHexagramIdAndPosition(Integer hexagramId, Integer yaoPosition) {
        // 参数校验
        if (hexagramId == null) {
            throw new IllegalArgumentException("卦象ID不能为空");
        }

        if (yaoPosition == null || yaoPosition < 1 || yaoPosition > 6) {
            throw new IllegalArgumentException("爻位必须为1-6之间的整数");
        }

        try {
            return yaoCiMapper.findByHexagramIdAndYaoPosition(hexagramId, yaoPosition);
        } catch (Exception e) {
            log.error("根据卦象ID和爻位获取爻辞失败: hexagramId={}, yaoPosition={}",
                    hexagramId, yaoPosition, e);
            throw new RuntimeException("根据卦象ID和爻位获取爻辞失败: " + e.getMessage());
        }
    }
    
    @Override
    public IPage<HexagramDO> searchHexagrams(String keyword, Integer pageNum, Integer pageSize) {
        // 参数校验
        if (!StringUtils.hasText(keyword)) {
            throw new IllegalArgumentException("搜索关键字不能为空");
        }

        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            List<HexagramDO> hexagrams = hexagramMapper.searchByKeyword(keyword);
            Page<HexagramDO> page = new Page<>(actualPageNum, actualPageSize);
            page.setRecords(hexagrams);
            page.setTotal(hexagrams.size());
            return page;
        } catch (Exception e) {
            log.error("搜索卦象失败: keyword={}, pageNum={}, pageSize={}",
                    keyword, actualPageNum, actualPageSize, e);
            throw new RuntimeException("搜索卦象失败: " + e.getMessage());
        }
    }
    
    @Override
    public IPage<HexagramDO> getHexagramsByFiveElements(String fiveElements, Integer pageNum, Integer pageSize) {
        // 参数校验
        if (!StringUtils.hasText(fiveElements)) {
            throw new IllegalArgumentException("五行属性不能为空");
        }

        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            List<HexagramDO> hexagrams = hexagramMapper.findByFiveElements(fiveElements);
            Page<HexagramDO> page = new Page<>(actualPageNum, actualPageSize);
            page.setRecords(hexagrams);
            page.setTotal(hexagrams.size());
            return page;
        } catch (Exception e) {
            log.error("根据五行属性获取卦象失败: fiveElements={}, pageNum={}, pageSize={}",
                    fiveElements, actualPageNum, actualPageSize, e);
            throw new RuntimeException("根据五行属性获取卦象失败: " + e.getMessage());
        }
    }
}